package com.wuzf.order.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 自定义的规则
 */
@Component
public class MyLB implements LoadBalance {


    private AtomicInteger atomicInteger = new AtomicInteger(0);


    private final int getAndIncrement() {
        int current;
        int next;

        // 自旋锁的使用，保证在多线程中可靠
        do {
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (atomicInteger.compareAndSet(current, next));
        return next;
    }


    @Override
    public ServiceInstance instance(List<ServiceInstance> list) {
        ServiceInstance instance = list.get(getAndIncrement() % list.size());
        return instance;
    }


}
